//
//  JKLeftViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit

class JKLeftViewController: JKBaseViewController {
    
    /** 设置按钮点击的block */
    public var settingBtnBlock: (() -> ())?
    
    /** 头像按钮点击的block */
    public var iconBtnBlock: (() -> ())?
    
    /** 收藏按钮点击的block */
    public var collectionBtnBlock: (() -> ())?
    
    /** 消息按钮点击的block */
    public var messageBtnBlock: (() -> ())?
    
    /** 选中cell的block */
    public var cellSelectedBlock: ((_ model: JKThemeModel, _ index: Int) -> ())?
    
    

    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var iconImageView: UIImageView!

    @IBOutlet weak var updateSkinButton: UIButton!
    
    @IBOutlet weak var nameButton: UIButton!
    
    @IBOutlet weak var downLoadToLocaleBtn: UIButton!
    
    @IBOutlet weak var progressLabel: UILabel!
    
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    @IBOutlet weak var nameTopCons: NSLayoutConstraint!
    
    lazy var themeNames = [String]()
    
    lazy var themeModels = [JKThemeModel]()
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        JKLog(message: key)
    }
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        updateUserIconAndName()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        
    }
    
    // MARK: - 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = JKColor(26, 31, 36)
        
        navBgView.isHidden = true
        navBackButton.isHidden = true
        
        nameTopCons.constant = JKStatusBarHeight + 18
        
        bottomCons.constant = JKIsIphoneX ? JKHomeIndicatorHeight + 8 : 8
        
        tableView.jk_adapt_iOS_11_scrollView()
        
        tableView.scrollsToTop = false
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0)
        
        tableView.backgroundColor = JKColor(26, 31, 36)
        
        updateUserIconAndName()
    }
    
    
    //MARK: - 加载数据
    override func loadNewData() {
        
        JKNetworkingTool.shared.requestGet(url: "themes", parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                self.showReloadView()
                
                self.reloadView.frame = CGRectMake(0, 107 + JKStatusBarHeight + 88, self.view
                    .width, JKScreenH - 38 - JKCurrentHomeIndicatorHeight - 107 - JKStatusBarHeight - 88)
                self.reloadView.backgroundColor = self.view.backgroundColor
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                self.showReloadView()
                
                self.reloadView.frame = CGRectMake(0, 107 + JKStatusBarHeight + 88, self.view
                    .width, JKScreenH - 38 - JKCurrentHomeIndicatorHeight - 107 - JKStatusBarHeight - 88)
                self.reloadView.backgroundColor = self.view.backgroundColor
                
                return
            }
            
            guard let themes = (json["others"]) as? [[String : AnyObject]] else {
                
                self.showReloadView()
                
                self.reloadView.frame = CGRectMake(0, 107 + JKStatusBarHeight + 88, self.view
                    .width, JKScreenH - 38 - JKCurrentHomeIndicatorHeight - 107 - JKStatusBarHeight - 88)
                self.reloadView.backgroundColor = self.view.backgroundColor
                
               return
            }
            
            guard let themeMds = [JKThemeModel].deserialize(from: themes) else {
                
                self.showReloadView()
                
                self.reloadView.frame = CGRectMake(0, 107 + JKStatusBarHeight + 88, self.view
                    .width, JKScreenH - 38 - JKCurrentHomeIndicatorHeight - 107 - JKStatusBarHeight - 88)
                self.reloadView.backgroundColor = self.view.backgroundColor
                
                return
            }
            
            self.hideReloadView()
            
            self.themeNames = (themes as NSArray).value(forKeyPath: "name") as! [String]
            
            self.themeModels = themeMds as! [JKThemeModel]
            
            self.tableView.reloadData()
            
            self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UITableViewScrollPosition.none)
        }
    }
    
    /** 更新用户信息 */
    func updateUserIconAndName() {
        
        let name = UserDefaults.standard.string(forKey: JKUserNameKey) ?? "未登录"
        nameButton.setTitle(name, for: UIControlState.normal)

        if !JKAccountManager.shared.isLogin {
            
            self.iconImageView.image = UIImage(named: "Setting_Avatar")?.jk_circleImage()
            
            return
        }
        
        let imgPath = ((NSHomeDirectory() as NSString).appendingPathComponent("Documents") as NSString).appendingPathComponent("userIcon.png")
        
        var img = UIImage(contentsOfFile: imgPath)
        
        if (img == nil) {
            
            img = UIImage(named: "myIcon")?.jk_circleImage()
        }
        
        self.iconImageView.image = img
    }
    
    // MARK: - 点击事件
    
    @IBAction func iconClick(_ sender: Any) {
        
        if iconBtnBlock != nil {
            
            iconBtnBlock!()
            
            tableView.reloadData()
        }
    }
    
    @IBAction func collectionBtnClick(_ sender: Any) {
        
        if collectionBtnBlock != nil {
            
            collectionBtnBlock!()
            
            tableView.reloadData()
        }
    }
    
    @IBAction func messageBtnClick(_ sender: Any) {
        
        if messageBtnBlock != nil {
            
            messageBtnBlock!()
            
            tableView.reloadData()
        }
    }
    
    @IBAction func settingBtnClick(_ sender: Any) {
        
        if settingBtnBlock != nil {
            
            settingBtnBlock!()
            
            tableView.reloadData()
        }
    }
    
    @IBAction func downLoadToLocaleBtnClick(_ sender: Any) {
        
        JKSQLiteManager.shared.downLoadToLocal()
        
        weak var weakSelf = self
        
        JKSQLiteManager.shared.cacheCompletedBlock = { (progressText) in
            
            self.downLoadToLocaleBtn.isUserInteractionEnabled = false
            self.progressLabel.isHidden = false
            
            weakSelf?.progressLabel.text = progressText
            
            if progressText == "100%" {
                
                UIView.animate(withDuration: 0.5, delay: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: {
                    
                    weakSelf?.progressLabel.alpha = 0
                    
                }, completion: { (_) in
                    
                    weakSelf?.downLoadToLocaleBtn.isUserInteractionEnabled = true
                    weakSelf?.progressLabel.isHidden = true
                    weakSelf?.progressLabel.alpha = 1
                })
            }
        }
    }
    
    @IBAction func updateSkinButtonClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        let skinValue = (sender.isSelected) ? JKNightSkinModelValue : JKDaySkinModelValue
        
        UserDefaults.standard.set(skinValue, forKey: JKCurrentSkinModelKey)
        UserDefaults.standard.synchronize()
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JKLeftViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.themeNames.count > 0 ? self.themeNames.count + 2 : 2
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        
        if (cell == nil) {
            
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            cell?.backgroundColor = nil
            cell?.textLabel?.textColor = JKSameRGBColor(186)
            let selectBkView = UIView()
            selectBkView.backgroundColor = JKColor(11, 16, 20)
            cell?.selectedBackgroundView = selectBkView
            
            cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        }
        
        if (indexPath.row == 0) {
            
            cell?.textLabel?.text = "首页"
            
        }else if (indexPath.row == 1){
            
            cell?.textLabel?.text = "专栏"
            
        }else{
            
            cell?.textLabel?.text = self.themeNames[indexPath.row-2]
        }
        
        return cell!
    }
}

extension JKLeftViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if cellSelectedBlock == nil {
            return
        }
        
        var model: JKThemeModel? = nil
        
        if indexPath.row > 1 {
            
            model = self.themeModels[indexPath.row - 2]
        }
        
        cellSelectedBlock!(model ?? JKThemeModel(), indexPath.row)
    }
}

extension JKLeftViewController {
    
    override func updateSkin() {
        
        self.updateSkinButton.isSelected = (currentSkinModel == JKNightSkinModelValue)
    }
}
